package com.rongc.client.freight.base.view.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.LogUtils;
import com.rongc.client.core.utils.SPUtil;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.request.api.LocationApi;
import com.rongc.client.freight.base.request.api.UpdateReadApi;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.view.fragment.HomeFragment;
import com.rongc.client.freight.base.view.fragment.MessageFragment;
import com.rongc.client.freight.base.view.fragment.MineFragment;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * Created by ccqx on 2017/6/29.
 */

public class HostActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{
    private FragmentTabHost mTabHost;
    private LayoutInflater layoutInflater;
    private Class fragmentArray[] = {HomeFragment.class,MessageFragment.class,MineFragment.class};
    private int mImageViewArray[] = {R.drawable.host_bottom_1,R.drawable.host_bottom_2,R.drawable.host_bottom_3};
    private int mTextviewArray[] = {R.string.host_tab_main,R.string.host_tab_message,R.string.host_tab_mine};
    boolean hasUnread = false;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    SPUtil.putString("lon", aMapLocation.getLongitude() + "");
                    SPUtil.putString("lat", aMapLocation.getLatitude() + "");
                    SPUtil.putString("ssq", StringUtils.getssqAddress(aMapLocation));
                    SPUtil.putString("address", aMapLocation.getAddress());

                    RequestManager.getInstance().call(new LocationApi(new LocationApi.LocationParams(
                            UniApplication.getInstance().getUserInfo().getUserId(),
                            aMapLocation.getLatitude() + "", aMapLocation.getLongitude() + ""),
                            respNullListener, errorListener));
                }
            }
        }
    };

    BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ImageView img = ((ImageView)mTabHost.getTabWidget().getChildTabViewAt(1).findViewById(R.id.tab_iv_image));
            if(intent.getBooleanExtra("unRead",false)){
                if(img != null){
                    hasUnread = true;
                    img.setImageResource(R.drawable.host_bottom_ring);
                }
            }else{
                if(img != null) {
                    hasUnread = false;
                    img.setImageResource(R.drawable.host_bottom_2);
                }
            }

        }
    };


    @Override
    public void onResume() {
        super.onResume();

        String uid = UniApplication.getInstance().getUserInfo().getUserId();
        if(StringUtils.isNotEmpty(uid)){
            // 绑定个人alias
            setAlias();
        }
        if(mTabHost!=null && StringUtils.isNotEmpty(mTabHost.getCurrentTabTag()))
        if(mTabHost.getCurrentTabTag().equals(mTextviewArray[0]+"")){
            if(getSupportFragmentManager().
                    findFragmentByTag(mTextviewArray[0]+"") != null)
            ((HomeFragment)getSupportFragmentManager().
                    findFragmentByTag(mTextviewArray[0]+"")).showData();
        }


    }

    Response.Listener<NullResult> respNullListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            LogUtils.i("error.getMessage(): " + error.getMessage());
        }
    };
    @Override
    public void initView() {
        layoutInflater = LayoutInflater.from(this);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        int count = fragmentArray.length;
        for(int i = 0; i < count; i++){
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]+"").setIndicator(getTabItemView(i));
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
        }

        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                if((mTextviewArray[1]+"").equals(tabId)){
                    sendBroadcast(new Intent("com.rongc.client.freight"));
                    if(hasUnread)
                    RequestManager.getInstance().call(new UpdateReadApi(new UpdateReadApi.UpdateReadParams(),
                            respNullListener, errorListener));
                }
            }
        });

        IntentFilter intent = new IntentFilter();
        intent.addAction("com.rongc.client.freight");
        registerReceiver(myReceiver,intent);

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(false);
//        mLocationOption.setOnceLocationLatest(true);
        if(StringUtils.isNotEmpty(SPUtil.getString("ssq"))){
            mLocationOption.setInterval(60000);
        }else{
            mLocationOption.setInterval(10000);
        }

        mLocationOption.setNeedAddress(true);
        mLocationClient.setLocationOption(mLocationOption);
//        mLocationClient.startLocation();
        choiceDWWrapper();
    }


    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index){
        View view = layoutInflater.inflate(R.layout.widget_host_tab, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.tab_iv_image);
        TextView mTxtTitle = (TextView) view.findViewById(R.id.tab_tv_content);
        imageView.setImageResource(mImageViewArray[index]);
        mTxtTitle.setText(mTextviewArray[index]);
        return view;
    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ActivityUtils.toast( "再按一次返回退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.gc();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK&&requestCode ==11){
            ActivityUtils.startActivity(this, LoginActivity.class);
            finish();
            System.exit(0);
        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_host;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    private void setAlias(){
        String alias = UniApplication.getInstance().getUserInfo().getUserId();
//		String alias = "system";
        if (TextUtils.isEmpty(alias)) {
            Log.i(TAG, "error_alias_empty");
            return;
        }
        /*if (!ExampleUtil.isValidTagAndAlias(alias)) {
            Log.i(TAG, "error_tag_gs_empty");
            return;
        }*/

        //调用 API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private static final String TAG = "JPush";
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    PushAgent mPushAgent = PushAgent.getInstance(UniApplication.getInstance());
                    boolean con = SPUtil.getBoolean("mute",true);
                    if(con)
                        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
                    else
                        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
                    mPushAgent.addAlias((String) msg.obj, "SLHY", new UTrack.ICallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                        }
                    });

//                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    Log.d(TAG, "Set tags in handler.");
//                JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };


    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choiceDWWrapper() {
        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            mLocationClient.startLocation();
        } else {
            EasyPermissions.requestPermissions(this, "定位选择需要以下权限:\n\n1.显示车源货源信息", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "打开GPS定位更准确", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「找车找货」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }


    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;
}
